<template>    
    <el-dialog
      style="top: -100px"
      title="维修上报"
      :visible.sync="visible"
      width="600px"
      :before-close="handleClose"
      class="announcement-edit-dialog"
    >
    <el-col style="position: relative;" :sm="12" :lg="6">
      <el-result v-if="form.status === 3" style="position: absolute; top: -70px; left: 420px;" icon="success"/>
      <el-result v-if="form.status === 4" style="position: absolute; top: -70px; left: 420px;" icon="error"/>
    </el-col>
    <el-timeline>
      <el-timeline-item :color="form.status === 0 ? '#0bbd87' : '#0bbd87'"   icon='el-icon-check' size="small" timestamp="待处理" placement="top">
        <el-form :disabled="form.status != 0" size="small" :model="form" style="right: 10px; font-weight: bold;" :rules="rules" ref="form" label-width="80px" label-position="top">
          <el-form-item style="padding: 0px;margin-bottom: 15px;" label="维修标题" prop="title">
            <el-input style="width: 500px; padding: 0px;" v-model="form.title" placeholder="维修标题"></el-input>
          </el-form-item>

          <el-form-item style="padding: 0px;margin-bottom: 15px;" label="维修问题描述" prop="description">
            <el-input style="width: 500px;padding: 0px;" v-model="form.description" placeholder="请输入维修问题描述"></el-input>
          </el-form-item>
  
          <el-form-item style="padding: 0px;margin-bottom: 15px;" label="位置" prop="hostelId">
              <el-select v-model="form.hostelId" placeholder="请选择位置">
                  <el-option
                    v-for="item in hostelOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
              </el-select>
          </el-form-item>

          <el-form-item style="padding: 0px;margin-bottom: 15px;" label="预约时间" prop="prebookStartTime">
            <el-cascader-panel v-model="form.prebookStartTime" style="width:360px" :options="options"></el-cascader-panel>
          </el-form-item>
  
          <el-form-item style="padding: 0px;margin-bottom: 15px;" label="上报图片" prop="reporterImage">
              <el-upload
                action="#"
                list-type="picture-card"
                :auto-upload="false"
                :on-change="handleChange"
                :before-upload="beforeUpload"
                :file-list="fileList"
                accept="image/*">
                  <i slot="default" class="el-icon-plus"></i>
                  <div slot="file" slot-scope="{file}">
                    <img
                      class="el-upload-list__item-thumbnail"
                      :src="file.url" alt=""
                    >
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-preview"
                        @click="handlePreviewTwo(file)"
                      >
                        <i class="el-icon-zoom-in"></i>
                      </span>
                      <span
                        v-if="!disabled"
                        class="el-upload-list__item-delete"
                        @click="handleRemove(file)"
                      >
                        <i class="el-icon-delete"></i>
                      </span>
                    </span>
                  </div>
              </el-upload>
              <el-dialog width="20%" :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
          </el-form-item>
        </el-form>  

        <span v-if="form.status == 0" style="top: 10px">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="submitForm('form')">上 报</el-button>
        </span>
      </el-timeline-item>

      <el-timeline-item :color="form.status !== 0 ? '#0bbd87' : '#ccc'" icon='el-icon-check' size="large" timestamp="处理中" placement="top">
        <el-card v-if="form.status === 0 ? false : true" style="margin-bottom:20px">
          <h4 style="margin-bottom:20px">维修人员： {{form.upkeepName}}</h4>
          <h4>维修人邮箱：{{form.upkeepEmail}}</h4>
        </el-card>
        <el-upload
          class="upload-demo"
          action="http://localhost:7001/ossFile/upload"
          :headers="headers"
          :on-preview="handlePreviewTwo"
          :on-remove="handleRemoveTwo"
          :file-list.sync="fileListTwo"
          list-type="picture"
          :before-upload="beforeUploadTwo"
          :on-success="handleSuccess"
          multiple>
          <el-button size="small" type="primary" v-if="form.upkeepId === user.id && form.status === 1">点击上传</el-button>
          <div slot="tip" v-if="form.upkeepId === user.id && form.status === 1" class="el-upload__tip">只能上传 jpg/png 文件，且不超过 500KB</div>
        </el-upload>

        <span v-if="form.status == 1 && form.upkeepId === user.id" style="padding-right: 40px">
          <el-button style="margin-top:20px" @click="open">取消订单</el-button>
          <el-button style="margin-top:20px" @click="openDialog" type="primary">维修完成</el-button>
        </span>

          <!-- 弹出框 -->
          <el-dialog title="请输入价格和备注" :visible.sync="isDialogOpen" width="30%"   append-to-body :modal-append-to-body="false">
            <el-form label-width="80px">
              <!-- 价格输入框 -->
              <el-form-item style="margin-right: 50px" label="价格">
                <el-input v-model="form.price" placeholder="请输入价格" @input="validatePrice"></el-input>
                <span class="error-text" v-if="priceError">{{ priceError }}</span>
              </el-form-item>

              <el-form-item style="margin-right: 50px" label="支付方式">
                <el-radio-group v-model="form.payWay">
                  <el-radio  :label="0">线上支付</el-radio>
                  <el-radio  :label="1">线下支付</el-radio>
                </el-radio-group>
              </el-form-item>

              <!-- 备注输入框 -->
              <el-form-item style="margin-right: 50px" label="备注">
                <el-input v-model="form.remark" placeholder="请输入备注" @input="validateRemark"></el-input>
                <span class="error-text" v-if="remarkError">{{ remarkError }}</span>
              </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
              <el-button @click="isDialogOpen = false">取消</el-button>
              <el-button type="primary" @click="confirmInput">确定</el-button>
            </span>
          </el-dialog>

      </el-timeline-item>
      <el-timeline-item :color="form.status !== 0 && form.status !== 1 ? (form.status === 4 ? 'rgb(248, 31, 28)' : '#0bbd87') : '#ccc'"  :icon=" form.status === 4 ? 'el-icon-close': 'el-icon-check'" size="large" timestamp="待支付" placement="top">
        <el-card v-if="form.status !== 0 && form.status !== 1">
          <h4 style="margin-bottom: 10px">支付方式： {{form.payWay === 0 ? '线上支付' : '线下支付'}} </h4>
          <h4 style="margin-bottom: 10px">支付金额： {{form.price ? form.price : 0}} </h4>
          <h4 v-if="form.status === 3 && form.payWay == 0" >支付成功： 通过支付宝支付 </h4>

          <span v-if="form.reporterId === user.id && form.status === 2" style="padding-right: 40px">
            <el-button style="margin-top:20px" @click="pay()" type="primary">支付</el-button>
          </span>
        </el-card>
      </el-timeline-item>
      <el-timeline-item :color="form.status === 3 || form.status === 4 ? '#0bbd87' : '#ccc'"  icon='el-icon-check' size="large" timestamp="已完成" placement="top">
        <el-card  v-if="form.status == 3 || form.status === 4">
          <h4>{{form.remark}}</h4>
        </el-card>
      </el-timeline-item>
    </el-timeline>
  </el-dialog>
    
</template>
  
  <script>
import { cloneDeep } from 'lodash';
import api from '@/api';
import { mapState,mapMutations } from "vuex"
import { values } from 'lodash';


  export default {  
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      formData: {
        type: Object,
        default: () => ({})
      }
    },
    data() {
      return {
        isDialogOpen: false,
        priceError: "",
        remarkError: "",

        headers: {},


        // { name: 'image1.jpg', url: 'https://med-10.oss-cn-beijing.aliyuncs.com/Snipaste_2023-02-18_20-30-47.png' }
        fileList: [],
        dialogImageUrl: '',
        dialogVisible: false,
        disabled: false,

        options: [
    {
        "value": "今天",
        "label": "今天",
        "children": [
            {
                "value": "09:00-11:00",
                "label": "09:00-11:00",
            },
            {
                "value": "11:00-13:00",
                "label": "11:00-13:00",
            },
            {
                "value": "13:00-15:00",
                "label": "13:00-15:00",
            },
            {
                "value": "15:00-17:00",
                "label": "15:00-17:00",
            },
            {
                "value": "17:00-19:00",
                "label": "17:00-19:00",
            }
        ]
    },
    {
        "value": "明天",
        "label": "明天",
        "children": [
            {
                "value": "09:00-11:00",
                "label": "09:00-11:00",
            },
            {
                "value": "11:00-13:00",
                "label": "11:00-13:00",
            },
            {
                "value": "13:00-15:00",
                "label": "13:00-15:00",
            },
            {
                "value": "15:00-17:00",
                "label": "15:00-17:00",
            },
            {
                "value": "17:00-19:00",
                "label": "17:00-19:00",
            }
        ]
    },
    {
        "value": "后天",
        "label": "后天",
        "children": [
            {
                "value": "09:00-11:00",
                "label": "09:00-11:00",
            },
            {
                "value": "11:00-13:00",
                "label": "11:00-13:00",
            },
            {
                "value": "13:00-15:00",
                "label": "13:00-15:00",
            },
            {
                "value": "15:00-17:00",
                "label": "15:00-17:00",
            },
            {
                "value": "17:00-19:00",
                "label": "17:00-19:00",
            }
        ]
    }
        ],

        form: {
          id:'',
          title:'',
          reporterId:'',
          reporterName:'',
          description: '',
          createTime:'',  
          upkeepId:'',
          upkeepName:'',
          reporterEmail:'',
          upkeepEmail:'',
          upkeepImage:"",
          hostelId:"",
          buildAndHostelName:'',
          prebookStartTime:[],
          prebookEndTime:'',
          reporterImage:'',
          remark:"",
          payWay:0,
        },
        hostelOptions:[],
        buildOptions:[],
        rules: {
          title: [
            { required: true, message: '请输入维修标题', trigger: 'blur' },
            { min: 2, max: 10, message: '请简略描述维修情况', trigger: 'blur' },
          ],
          description: [
            { required: true, message: '请输入维修问题描述', trigger: 'blur' },
            { min: 2, max: 100, message: '请详细描述维修情况', trigger: 'blur' },
          ],
          hostelId: [
            { required: true, message: '请选择位置', trigger: 'blur' },
          ],
          prebookStartTime:[
            { required: true, message: '请选择预约时间', trigger: 'blur' },
          ]
        },

        fileListTwo: [
          // { name: 'image1.jpg', url: 'https://med-10.oss-cn-beijing.aliyuncs.com/Snipaste_2023-02-18_20-30-47.png' }
          // {
          //   name: "food2.jpeg",
          //   url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100"
          // }
        ]
      }
    },
    created(){
      this.getReceivers()
      this.getHostel()
      this.updateOptions()
      this.headers = {'token': this.user.token}
    },
    computed:{
      ...mapState("login",["user"])
    },
    methods: {

        ...mapMutations("login",["setUser","setUserNull"]),
        pay(){
          if(!this.form.id || !this.form.price){
            return
          }
          api.apiPay(this.form.id,this.form.price).then(res =>{
                  // 创建一个新的窗口，并写入返回的 HTML 表单
                let newWindow = window.open();
                newWindow.document.open();
                newWindow.document.write(res);
                newWindow.document.close();
          }).catch(error => {
            console.error("支付请求失败:", error);
          });
        },

        openDialog() {
          console.log(this.form)
          this.isDialogOpen = true;
        },
        validatePrice() {
          if (!/^\d+(\.\d{1,2})?$/.test(this.form.price)) {
            this.priceError = "请输入有效的小数 (最多两位小数)";
          } else {
            this.priceError = "";
          }
        },
        validateRemark() {
          if (this.form.remark.length < 2 || this.form.remark.length > 30) {
            this.remarkError = "备注需在 2-30 个字符之间";
          } else {
            this.remarkError = "";
          }
        },
        confirmInput() {
          this.validatePrice();
          this.validateRemark();
          if (!this.priceError && !this.remarkError) {
            this.isDialogOpen = false; // 关闭弹窗

            if(this.form.payWay === null){
              this.$message.error(`请选择支付方式`);
              return
            }

            var status = this.form.payWay === 0 ? 2 : 3;
            console.log(this.form.payWay+"====",status)

            if(!this.fileListTwo || this.fileListTwo.length === 0){
              this.$message.error(`请上传维修图片`);
              return
            }else{
              var urlList = []
              this.fileListTwo.forEach(file =>{
                  urlList.push(file.url)
              })
              this.form.upkeepImage = urlList.join(",")
            }

            //提交
            api.saveOrUpdateUpkeep({'remark': this.form.remark,'status': status,'id': this.form.id,
             'upkeepImage': this.form.upkeepImage, 'price': this.form.price,'payWay': this.form.payWay}).then(res =>{
                  if(res.type === 'error'){
                    this.$message.error(res.message)
                  }else if(res.data.code === 200){
                      location.reload();
                      this.$message({
                        message: '维修完成',
                        type: 'success'
                      })
                  }else{
                    this.$message.error(res.data.message)
                  }
            })
          }
        },

      //设置日期格式
      formatDate(date) {
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          return `${year}-${month}-${day}`;
      },


        //取消订单
        open() {
            this.$prompt('请输入取消原因', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              inputPattern: /^\S.{1,18}\S$/,
              inputErrorMessage: '格式不正确，禁止首尾空格（3~20位非空白字符）'
            }).then(({ value }) => {
              this.form.remark = value
              api.saveOrUpdateUpkeep({'remark': value,'status':'3','id': this.form.id}).then(res =>{
                  if(res.type === 'error'){
                    this.$message.error(res.message)
                  }else if(res.data.code === 200){
                      location.reload();
                      this.$message({
                        message: '订单取消成功',
                        type: 'success'
                      })
                  }else{
                    this.$message.error(res.data.message)
                  }
              })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '取消输入'
              });       
            });
          },        

          //上传图片
          uploadFile(file){
                //将文件上传到后端
                api.uploadFile(file.raw).then(res =>{
                    if(res.type === 'error'){
                        this.$message.error(res.message)
                    }else if(res.data.code === 200){
                        const url = res.data.data.url;
                        this.fileList[this.fileList.length-1].url = url
                        this.$message({
                            message: res.data.message,
                            type: 'success'
                        });
                    }else{
                        this.$message.error(res.data.message)
                    }
                })    
          },


        // 处理文件变化
        handleChange(file, fileList) {
          if(this.fileList.length >= 2){
            this.$message.error('只能上传两张图片!');
            this.fileList = fileList.slice(0, 2); // 强制截断
            return
          } 
          this.fileList = fileList;
          this.uploadFile(file)
        },
        
        // 限制只能上传图片
        beforeUpload(file) {
          const isImage = file.type.includes('image/');
          if (!isImage) {
            this.$message.error('只能上传图片文件!');
          }
          return isImage;
        },
        
        // 删除图片
        handleRemove(file) {
          if(this.form.status !== 0){
            this.$message.error('图片不能修改!');
            return
          }
          const index = this.fileList.indexOf(file);
          if (index !== -1) {
            this.fileList.splice(index, 1);
          }
          // 如果有后端删除接口，可以在这里调用
          // this.deleteImage(file.name);
        },
        
        // 预览图片
        handlePictureCardPreview(file) {
          this.dialogImageUrl = file.url;
          this.dialogVisible = true;
        },


        setSelectedTime() {
            if (!this.form.prebookStartTime || this.form.prebookStartTime.length === 0) return;

            const [dateStr, timeStr] = this.form.prebookStartTime.split(",");
            const now = new Date();
            const targetDate = new Date(dateStr);

            // 只保留年月日进行比较
            const formatDate = (date) => new Date(date.getFullYear(), date.getMonth(), date.getDate());

            const today = formatDate(now);
            const tomorrow = new Date(today);
            tomorrow.setDate(today.getDate() + 1);
            const dayAfterTomorrow = new Date(today);
            dayAfterTomorrow.setDate(today.getDate() + 2);

            let dayLabel = null;
            if (formatDate(targetDate).getTime() === today.getTime()) {
              dayLabel = "今天";
            } else if (formatDate(targetDate).getTime() === tomorrow.getTime()) {
              dayLabel = "明天";
            } else if (formatDate(targetDate).getTime() === dayAfterTomorrow.getTime()) {
              dayLabel = "后天";
            }

            if (dayLabel) {
                this.form.prebookStartTime = [dayLabel, timeStr];
                // 更新 options，禁用其他选项，只选中匹配的时间段
                this.options.forEach(option => {
                  option.children.forEach(child => {
                    if (option.value === dayLabel) {
                      // 选中匹配的时间段
                      if (child.value === timeStr) {
                        this.form.prebookStartTime = [dayLabel, child.value]
                        // this.$set(this.form, 'prebookStartTime', [dayLabel, child.value]);
                        child.disabled = false;
                      } else {
                        child.disabled = true;
                      }
                    } else {
                      child.disabled = true;
                    }
                  });
                });
              }
          },



          updateOptions() {
            const now = new Date();
            const currentTimestamp = now.getTime(); // 当前时间的时间戳
            const todayLabel = ["今天", "明天", "后天"];

            this.options = todayLabel.map((day, index) => {
              const date = new Date();
              date.setDate(now.getDate() + index); // 计算今天、明天、后天的日期

              return {
                value: day,
                label: day,
                children: [
                  "09:00-11:00",
                  "11:00-13:00",
                  "13:00-15:00",
                  "15:00-17:00",
                  "17:00-19:00"
                ].map(time => {
                  const [startHour, startMinute] = time.split("-")[0].split(":").map(Number);
                  
                  // 构造当天这个时间段的 Date 对象
                  const timeDate = new Date(date.getFullYear(), date.getMonth(), date.getDate(), startHour, startMinute);
                  const timeTimestamp = timeDate.getTime(); // 获取该时间段的时间戳
                  
                  // 禁用规则：如果是今天，并且当前时间已经超过了这个时间段的起始时间，则禁用
                  const disabled = index === 0 && currentTimestamp >= timeTimestamp;
                  
                  return { value: time, label: time, disabled };
                })
              };
            });
          },


      submitForm(form) {
        this.$refs[form].validate((valid) => {
          if (valid) {
            //处理预约时间
            this.form.prebookEndTime = this.convertRelativeDate(this.form.prebookStartTime.join(","))
      
            //处理上报图片
            if(this.fileList && this.fileList.length > 0){
              var urlList = []
              this.fileList.forEach(file =>{
                  urlList.push(file.url)
              })
              this.form.reporterImage = urlList.join(",")
            }

            this.form.reporterId = this.user.id
            
            this.form.prebookStartTime = ''
            api.saveOrUpdateUpkeep(this.form).then(res =>{
              if(res.type === 'error'){
                this.$message.error(res.message)
              }else if(res.data.code === 200){
                  location.reload();
                  this.$message({
                    message: '操作成功',
                    type: 'success'
                  })
              }else{
                this.$message.error(res.data.message)
              }
            })
          } else {
            this.$message.error('请完善表单信息');
            return false;
          }
        });
      },

        // 将相对日期转换为具体日期
        convertRelativeDate(inputStr) {
          if (!inputStr) return '';
          
          // 拆分日期部分和时间部分
          const [datePart, timeRange] = inputStr.split(',');
          
          // 计算目标日期
          const today = new Date();
          const targetDate = new Date(today);
          
          switch (datePart) {
            case '明天':
              targetDate.setDate(today.getDate() + 1);
              break;
            case '后天':
              targetDate.setDate(today.getDate() + 2);
              break;
            // 默认处理"今天"和其他情况
          }
          
          // 格式化为 YYYY-M-D
          const formattedDate = `${targetDate.getFullYear()}-${targetDate.getMonth() + 1}-${targetDate.getDate()}`;
          
          // 返回组合结果
          return `${formattedDate},${timeRange}`;
        },

      handleClose() {
        // 手动清空表单
        this.form = {
          id:'',
          title:'',
          reporterId:'',
          reporterName:'',
          description: '',
          createTime:'',
          upkeepId:'',
          upkeepName:'',
          upkeepEmail:'',
          hostelId:"",
          buildAndHostelName:'',
          prebookStartTime:[],
          prebookEndTime:'',
          reporterImage:'',
          payWay:0,
          status: 0,
          remark:'',
        };
        this.options= [
    {
        "value": "今天",
        "label": "今天",
        "children": [
            {
                "value": "09:00-11:00",
                "label": "09:00-11:00",
            },
            {
                "value": "11:00-13:00",
                "label": "11:00-13:00",
            },
            {
                "value": "13:00-15:00",
                "label": "13:00-15:00",
            },
            {
                "value": "15:00-17:00",
                "label": "15:00-17:00",
            },
            {
                "value": "17:00-19:00",
                "label": "17:00-19:00",
            }
        ]
    },
    {
        "value": "明天",
        "label": "明天",
        "children": [
            {
                "value": "09:00-11:00",
                "label": "09:00-11:00",
            },
            {
                "value": "11:00-13:00",
                "label": "11:00-13:00",
            },
            {
                "value": "13:00-15:00",
                "label": "13:00-15:00",
            },
            {
                "value": "15:00-17:00",
                "label": "15:00-17:00",
            },
            {
                "value": "17:00-19:00",
                "label": "17:00-19:00",
            }
        ]
    },
    {
        "value": "后天",
        "label": "后天",
        "children": [
            {
                "value": "09:00-11:00",
                "label": "09:00-11:00",
            },
            {
                "value": "11:00-13:00",
                "label": "11:00-13:00",
            },
            {
                "value": "13:00-15:00",
                "label": "13:00-15:00",
            },
            {
                "value": "15:00-17:00",
                "label": "15:00-17:00",
            },
            {
                "value": "17:00-19:00",
                "label": "17:00-19:00",
            }
        ]
    }
        ],
        this.fileList = []
        // 重置表单验证状态
        this.$refs['form'].resetFields();
        this.$emit('updateFormData', {});
        this.$emit('update:visible', false);
      },

        //查询楼宇信息
        getReceivers() {
          return new Promise((resolve, reject) => {
              api.buildListAll().then(res => {
                if (res.type === 'error') {
                  this.$message.error(res.message);
                  reject(res.message);
                } else if (res.data.code === 200) {
                  const tableData = res.data.data.buildInfos;
                  this.buildOptions = tableData.map(item => ({
                    value: item.id,
                    label: item.buildingName + "-" + item.unit
                  }));
                  resolve();
                } else {
                  this.$message.error(res.data.message);
                  reject(res.data.message);
                }
              });
          });
        },      

        //查询房屋信息
        getHostel() {
          return new Promise((resolve, reject) => {
              api.hostelList({userId: this.user.id}).then(res => {
                if (res.type === 'error') {
                  this.$message.error(res.message);
                  reject(res.message);
                } else if (res.data.code === 200) {
                  const tableData = res.data.data.hostelInfos;

                  const optionsMap = this.buildOptions.reduce((map, option) => {
                        map[option.value] = option.label;
                        return map;
                  }, {});
                  tableData.forEach(item => {
                    if(item.buildId){
                        const buildName = optionsMap[item.buildId];
                        if(buildName){
                          this.hostelOptions.push({
                            value: item.id,
                            label: buildName + "-" + item.hostelCode
                          });
                        }
                    }
                  })
                  resolve();
                } else {
                  this.$message.error(res.data.message);
                  reject(res.data.message);
                }
              });
          });
        },

        // 预览文件
        handlePreview(file) {
          window.open(file.url); // 在新窗口打开图片
        },

        handlePreviewTwo(file) {
          const w = window.open("", "_blank", "width=800,height=600,top=100,left=100");

          // 构建 HTML 结构（居中 + 阴影背景）
          const html = `
            <!DOCTYPE html>
            <html>
              <head>
                <style>
                  body {
                    margin: 0;
                    padding: 0;
                    background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色遮罩 */
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    height: 100vh;
                  }
                  .preview-container {
                    background: white;
                    padding: 10px;
                    border-radius: 4px;
                    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
                  }
                  .preview-container img {
                    max-width: 100%;
                    max-height: 90vh; /* 限制高度，避免超出屏幕 */
                    display: block;
                  }
                </style>
              </head>
              <body>
                <div class="preview-container">
                  <img src="${file.url}" />
                </div>
              </body>
            </html>
          `;

          w.document.write(html);
          w.document.close(); // 确保文档写入完成
        },

        // 移除文件
        handleRemoveTwo(file, fileList) {
          if(this.form.status !== 2){
            this.$message.error('禁止删除图片');
              // 关键：恢复原来的文件列表，避免被清空
            this.$nextTick(() => {
              this.fileListTwo = [...this.fileListTwo];
            });

            return false;
          }
          console.log("删除文件:", file);
          this.fileListTwo = fileList; // 确保 fileListTwo 也更新
        },  

        // 上传前的校验
        beforeUploadTwo(file) {
          const isJPGorPNG = file.type === "image/jpeg" || file.type === "image/png";
          const isLt500KB = file.size / 1024 <= 500; // 500KB

          if(this.fileListTwo.length >= 2){
            this.$message.error('只能上传两张图片!');
            return false
          } 

          if (!isJPGorPNG) {
            this.$message.error("上传失败：只能上传 JPG/PNG 格式的图片！");
            return false;
          }
          if (!isLt500KB) {
            this.$message.error("上传失败：图片大小不能超过 500KB！");
            return false;
          }

          return true; // 允许上传
        },

        // 上传成功后添加到 fileListTwo
        handleSuccess(response, file, fileListTwo) {
          this.fileListTwo.push({
            name: response.data.url.split('/').pop(),
            url: response.data.url // 生成本地预览地址
          });
        }
            
    },
    watch: {
        // 监听 formData 的变化
        formData: {
            handler(newVal) {
                if (newVal && Object.keys(newVal).length > 0) {
                    // 深拷贝 formData 并赋值给 ruleForm
                    this.form = cloneDeep(newVal);
                    if(this.form.reporterImage){
                      this.form.reporterImage.split(",").forEach(file =>{
                        this.fileList.push({
                          url: file
                        })
                      })
                    }
                    if(this.form.upkeepImage){
                      console.log(this.form.upkeepImage)
                      this.form.upkeepImage.split(",").forEach(file =>{
                        this.fileListTwo.push({
                          name: this.formatDate(new Date())+".png",
                          url: file
                        })
                      })
                    }
                    if(this.form.status !== 0){
                      this.hostelOptions = [{
                        value: this.form.hostelId,
                        label: this.form.buildAndHostelName
                      }]
                    }
                    if(this.form.prebookStartTime){
                      this.setSelectedTime()
                    }
        
                }
            },
            immediate: true, // 立即执行一次
            deep: true, // 深度监听
        },
        // 监听 form.status 的变化
        'form.status': {
            handler(newStatus) {
              this.form.status = newStatus
            },
            immediate: true
        },
    },
  }
  </script>
  
  <style scoped>
  .error-text {
    color: red;
    font-size: 12px;
  }
  .float{
    color: #0bbd87
  }
  .announcement-edit-dialog >>> .el-dialog__body {
    padding: 20px 30px;
  }
  
  .editor-wrapper {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    overflow: hidden;
  }
  
  .editor-toolbar {
    border-bottom: 1px solid #dcdfe6;
    background-color: #f5f7fa;
  }
  
  .editor-content {
    min-height: 300px;
    max-height: 500px;
    overflow-y: auto;
  }
  
  .editor-form-item >>> .el-form-item__content {
    line-height: normal;
  }
  
  .line {
    line-height: 36px;
    color: #909399;
  }
  </style>